//
//  JSViewController44.swift
//  RXSwiftTest
//
//  Created by ZhangBo on 2019/6/18.
//  Copyright © 2019 ZhangBo. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxDataSources

class JSViewController44: BaseViewController {
    let disposeB = DisposeBag()
    var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        test6()
    }

}

//三、将结果转为 JSON 对象

extension JSViewController44 {
    //1，通过 rx.response 请求数据
    fileprivate func test1() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)
        //创建请求对象
        let request = URLRequest(url: url!)

        //创建并发起请求
        URLSession.shared.rx.data(request: request).subscribe(onNext: {
            data in
            let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
                as! [String: Any]
            print("--- 请求成功！返回的如下数据 ---")
            print(json!)
        }).disposed(by: disposeB)
    }

    fileprivate func test2() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)
        //创建请求对象
        let request = URLRequest(url: url!)

        //创建并发起请求
        URLSession.shared.rx.data(request: request)
            .map {
                try JSONSerialization.jsonObject(with: $0, options: .allowFragments)
                    as! [String: Any]
            }
            .subscribe(onNext: {
                data in
                print("--- 请求成功！返回的如下数据 ---")
                print(data)
            }).disposed(by: disposeB)
    }

    fileprivate func test3() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)
        //创建请求对象
        let request = URLRequest(url: url!)

        //创建并发起请求
        URLSession.shared.rx.json(request: request).subscribe(onNext: {
            data in
            let json = data as! [String: Any]
            print("--- 请求成功！返回的如下数据 ---")
            print(json)
        }).disposed(by: disposeB)
    }
}

extension JSViewController44 {
    fileprivate func test4() {
        //创建表格视图
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //创建一个重用的单元格
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)

        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)
        //创建请求对象
        let request = URLRequest(url: url!)

        //获取列表数据
        let data = URLSession.shared.rx.json(request: request).map { result -> [[String: Any]] in
            if let data = result as? [String: Any],
               let channels = data["channels"] as? [[String: Any]] {
                return channels
            } else {
                return []
            }
        }

        //将数据绑定到表格
        data.bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
            cell.textLabel?.text = "\(row)：\(element["name"]!)"
            return cell
        }.disposed(by: disposeB)
    }


    fileprivate func test5() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)
        //创建请求对象
        let request = URLRequest(url: url!)

        //创建并发起请求
        URLSession.shared.rx.json(request: request).mapObject(type: Douban.self).subscribe(onNext: { (douban: Douban) in
            if let channels = douban.channels {
                print("--- 共\(channels.count)个频道 ---")
                for channel in channels {
                    if let name = channel.name, let channelId = channel.channelId {
                        print("\(name) （id:\(channelId)）")
                    }
                }
            }
        }).disposed(by: disposeB)
    }
}

//四，将结果映射成自定义对象
extension JSViewController44 {
    fileprivate func test6() {
        //创建表格视图
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //创建一个重用的单元格
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)

        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string: urlString)
        //创建请求对象
        let request = URLRequest(url: url!)

        //获取列表数据
        let data = URLSession.shared.rx.json(request: request).mapObject(type: Douban.self).map {
            $0.channels ?? []
        }

        //将数据绑定到表格
        data.bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
            cell.textLabel?.text = "\(row)：\(element.name!)"
            return cell
        }.disposed(by: disposeB)
    }

}
